import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:封装DataSource单例模式
 * User: lenovo
 * Date: 2022-12-05
 * Time: 10:34
 */
public class DbUtil{
    private static volatile DataSource dataSource = null;
    private DbUtil(){

    }
    private static DataSource getDataSource(){
        if (dataSource == null) {
            synchronized (DbUtil.class) {
                if (dataSource == null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/blog_system?characterEncoding=utf8&UseSSL=false");
                    ((MysqlDataSource)dataSource).setUser("root");
                    ((MysqlDataSource)dataSource).setPassword("");
                }
            }
        }
        return dataSource;
    }
//    建立连接
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }
//    关闭资源
    public static void close(ResultSet resultSet, PreparedStatement statement,Connection connection){
//        如果对象不为空就关闭,为空就什么也不做
      if (resultSet != null){
          try {
              resultSet.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }

      if (statement != null){
          try {
              statement.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }

      if (connection != null){
          try {
              connection.close();
          } catch (SQLException e) {
              e.printStackTrace();
          }
      }
    }

}
